﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using VotesResults.Models;

namespace VotesResults.Daos.EntityFramework
{
    public class GroupDao : IGroupDao
    {
        public List<Group> Load()
        {
            using (VotesResultsEntities db = new VotesResultsEntities())
            {
                return db.Group.ToList();
            }
        }

        public List<GroupModel> LoadVoted(int voteId)
        {
            using (VotesResultsEntities db = new VotesResultsEntities())
            {
                // TODO: Сделать группировку по вопросам из опроса
                return db.RelVoteQuestionGroupSession
                    .Where(r => r.VoteId == voteId)
                    .GroupBy(x => x.GroupId)
                    .Select(x => 
                        new
                            {
                                GroupName = db.Group.FirstOrDefault(g => g.Id == x.Key).Name, 
                                VotesCount = x.Count()
                            })
                    .Select(x => 
                        new GroupModel
                            {
                                GroupName = x.GroupName,
                                VotesCount = x.VotesCount
                            }).ToList();
            }
        }

        public Group Get(int id)
        {
            using (VotesResultsEntities db =new VotesResultsEntities())
            {
                return db.Group.FirstOrDefault(m => m.Id == id);
            }
        }

        public void Add(Group group)
        {
            using (VotesResultsEntities db = new VotesResultsEntities())
            {
                db.AddToGroup(group);
                db.SaveChanges();
            }
        }

        public void Update(Group group)
        {
            using (VotesResultsEntities db = new VotesResultsEntities())
            {
                Group record = db.Group.FirstOrDefault(m => m.Id == group.Id);
                record.Name = group.Name;
                db.SaveChanges();
            }
        }

        public void Remove(int id)
        {
            using (VotesResultsEntities db = new VotesResultsEntities())
            {
                Group record = db.Group.FirstOrDefault(m => m.Id == id);
                if (record != null) db.DeleteObject(record);
                db.SaveChanges();
            }
        }
    }
}